package com.bq.gametrade.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.utils.DateUtils;
import com.bq.gametrade.utils.MD5Util;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.utils.StringUtils;
import com.bq.gametrade.view.PayPasswordValidationView;

import java.util.HashMap;
import java.util.Map;

public class SendRedEnvelopeActivity extends BaseActivity implements View.OnClickListener{

    private LinearLayout layBack;
    private TextView tvTitle;
    private EditText edMoneyCount,etLeaveMessage;
    private Button btnSenRedEnvelope;
    private RadioGroup rg;
    private String redEnvolopeType = "",friendAccount= "";
    private InputMethodManager inputMethodManager;
    private LoadingProgressDialog progressDialog;
    private UserInfoDetails userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.redEnvelope_bg));
        }
        setContentView(R.layout.activity_send_redenvelope);
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            application.setUserInfo(null);
            finish();
        }
        progressDialog = new LoadingProgressDialog(this,"正在支付···");
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        friendAccount = getIntent().getStringExtra("friendAccount");
        if (friendAccount.equals("")) {
            toastShow("获取好友信息出错，请重新进入");
            finish();
        }
        initView();
    }


    private void initView() {
        layBack = serchViewById(R.id.lay_back);
        layBack.setOnClickListener(this);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("发红包");
        edMoneyCount = serchViewById(R.id.et_moneyCount);
        etLeaveMessage = serchViewById(R.id.et_lLeaveMessage);
        btnSenRedEnvelope = serchViewById(R.id.btn_sendRedEnvelope);
        btnSenRedEnvelope.setOnClickListener(this);
        btnSenRedEnvelope.setClickable(false);
        edMoneyCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(edMoneyCount.getText().toString().length()>0){
                    if (Double.parseDouble(edMoneyCount.getText().toString()) > 0) {
                        btnSenRedEnvelope.setBackgroundResource(R.drawable.bg_btn_red_selector);
                        btnSenRedEnvelope.setClickable(true);
                    } else {
                        btnSenRedEnvelope.setBackgroundResource(R.drawable.bg_btn_red_selector_no);
                        btnSenRedEnvelope.setClickable(false);
                    }
                }else {
                    btnSenRedEnvelope.setBackgroundResource(R.drawable.bg_btn_red_selector_no);
                    btnSenRedEnvelope.setClickable(false);
                }


                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        edMoneyCount.setText(s);
                        edMoneyCount.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edMoneyCount.setText(s);
                    edMoneyCount.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edMoneyCount.setText(s.subSequence(0, 1));
                        edMoneyCount.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        rg = serchViewById(R.id.rg_pay);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton =(RadioButton) findViewById(group.getCheckedRadioButtonId());
                if (radioButton.getText().toString().equals("余额")) {
                    redEnvolopeType = "0";
                } else {
                    redEnvolopeType = "1";
                }
            }
        });
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_back:
                finish();
                break;
            case R.id.btn_sendRedEnvelope:
                inputMethodManager.hideSoftInputFromWindow(edMoneyCount.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                inputMethodManager.hideSoftInputFromWindow(etLeaveMessage.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if(edMoneyCount.getText().toString().equals("0")){
                    toastShow("金额输入不正确");
                    return;
                }
                if(redEnvolopeType.equals("")){
                    toastShow("发送红包金额类型还未选择");
                    return;
                }
                if(redEnvolopeType.equals("0")&&Double.parseDouble(edMoneyCount.getText().toString())>Double.parseDouble(application.getUserInfo().userMoney)){
                    toastShow("您没有那么多余额了，快去充值吧");
                    return;
                }
                if (redEnvolopeType.equals("1") &&  !StringUtils.isInteger(edMoneyCount.getText().toString())) {
                    //转余额判断
                    toastShow("鱼券必须为整数");
                    return;
                }

                if (redEnvolopeType.equals("1") && Double.parseDouble(edMoneyCount.getText().toString()) > Double.parseDouble(application.getUserInfo().userCard)) {
                    //转余额判断
                    toastShow("您没有那么多鱼券了，快去充值吧");
                    return;
                }
                if (!NetworkUtils.isNetworkAvailable(SendRedEnvelopeActivity.this)) {
                    toastShow("当前网络异常");
                    return;
                }
                toPay(MD5Util.md5(DateUtils.getTimestamp()+userInfo.account+"android"));
                break;
        }
    }



    /**
     * 验证支付密码-----start
     */

    private void toPay(final  String luckId){
        final PayPasswordValidationView payPasswordValidationView = new PayPasswordValidationView(SendRedEnvelopeActivity.this,userInfo,progressDialog);
        payPasswordValidationView.showAtLocation(SendRedEnvelopeActivity.this.findViewById(R.id.activity_sendRedEnvelope),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        payPasswordValidationView.backgroundAlpha(0.6f);
        payPasswordValidationView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                payPasswordValidationView.backgroundAlpha(1f);
            }
        });

        payPasswordValidationView.setOnFinishInputPayPassword(new PayPasswordValidationView.OnPayPasswordInputFinish() {
            @Override
            public void inputFinish(String status) {
                if (status.equals("0")) {
                    sendRedEnvelope(luckId);
                }
            }
        });
    }

    /**
     * end
     **/

    private void closeDialog(){
        if(progressDialog !=null){
            progressDialog.dismiss();
        }
    }


    private void sendRedEnvelope(String luckId) {
        Log.e("wu","+    "+luckId);
        String leaveMessage = etLeaveMessage.getText().toString();
        if(leaveMessage.equals("")){
            leaveMessage = etLeaveMessage.getHint().toString();
        }else {
            leaveMessage = etLeaveMessage.getText().toString();
        }

        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("account", friendAccount);
        params.put("num", edMoneyCount.getText().toString());
        params.put("type", redEnvolopeType);
        params.put("title", Base64.encodeToString(leaveMessage.getBytes(),0) );
        params.put("luckId",luckId);
        VRHttp.sendRequest(SendRedEnvelopeActivity.this, HttpLink.SEND_REDENVELOPE, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if(response != null){
                    ResponseBean bean =(ResponseBean)response;
                    if(bean.status.equals("0")){
                        toastShow("恭喜！发送成功！");
                        finish();
                    }else if(bean.status.equals("1")){
                        toastShow("发送失败！请重试");
                    }else if(bean.status.equals("99")){
                        toastShow("登录超时，请登录之后不再试");
                        application.setUserInfo(null);
                        startActivity(new Intent(SendRedEnvelopeActivity.this,LoginActivity.class));
                        finish();
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeDialog();
            }
        });
    }

}
